package com.killer.view;

import com.killer.servlet.ServletRequest;

import java.io.IOException;
import java.io.InputStream;

/**
 * 将请求过来的信息封装成request对象
 */
public class Request implements ServletRequest{

    /**
     * 请求方式
     */
    private String method;

    /**
     * 资源路径
     */
    private String path;

    /**
     * 虚拟主机
     */
    private String host;

    /**
     * 输入流
     */
    private InputStream inputStream;

    public Request(InputStream inputStream) {
        this.inputStream=inputStream;
        try {
            int total=inputStream.available();
            if (total == 0) {
                Thread.sleep(1000);
                //防止请求先到，但是具体数据还在传输的情况
                total=inputStream.available();
            }
            byte[] bytes = new byte[total];
            inputStream.read(bytes);
            String data = new String(bytes);
            String[] rows = data.split(System.getProperty("line.separator"));
            for (String row : rows) {
                if (row.startsWith("GET") || row.startsWith("POST")) {
                    String[] requestData = row.split(" ");
                    method=requestData[0];
                    path=requestData[1];
                }
                if (row.startsWith("Host")) {
                    String[] requestData = row.split(" ");
                    host=requestData[1].split(":")[0];
                }
            }
        } catch (IOException e) {
            throw new RuntimeException("读取输入流数据失败");
        } catch (InterruptedException e) {
            throw new RuntimeException("读取输入流数据失败");
        }
    }

    @Override
    public String getRequestMethod() {
        return method;
    }

    @Override
    public String getRequestPath() {
        return path;
    }

    public InputStream getInputStream() {
        return inputStream;
    }

    public void setInputStream(InputStream inputStream) {
        this.inputStream = inputStream;
    }

    public String getMethod() {
        return method;
    }

    public void setMethod(String method) {
        this.method = method;
    }

    public String getPath() {
        return path;
    }

    public void setPath(String path) {
        this.path = path;
    }

    public String getHost() {
        return host;
    }

    public void setHost(String host) {
        this.host = host;
    }
}
